<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入消息标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择消息状态"
          clearable
          size="small"
        >
          <el-option label="未读" value="0" />
          <el-option label="已读" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择消息类型"
          clearable
          size="small"
        >
          <el-option label="系统通知" value="0" />
          <el-option label="个人消息" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:message:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleReadBatch"
          v-hasPermi="['system:message:read']"
          >标记已读</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['system:message:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="messageList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="消息ID" align="center" prop="messageId" />
      <el-table-column
        label="标题"
        align="center"
        prop="title"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="内容"
        align="center"
        prop="content"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="消息类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="typeOptions" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:message:query']"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:message:edit']"
            v-if="scope.row.status !== '1'"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleRead(scope.row)"
            v-hasPermi="['system:message:read']"
            v-if="scope.row.status !== '1'"
            >已读</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:message:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看消息详情对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="viewOpen"
      width="600px"
      append-to-body
    >
      <div class="message-detail">
        <h3 class="message-title">{{ form.title }}</h3>
        <div class="message-meta">
          <span>类型：{{ form.typeLabel }}</span>
          <span>时间：{{ parseTime(form.createTime) }}</span>
        </div>
        <div class="message-content" v-html="form.content"></div>
      </div>
    </el-dialog>

    <!-- Add/Edit dialog -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入消息标题" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择消息类型">
            <el-option label="系统通知" value="0" />
            <el-option label="个人消息" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="接收人" prop="receiverId" v-if="form.type === '1'">
          <el-select
            v-model="form.receiverId"
            placeholder="请选择接收人"
            filterable
          >
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import {
  listMessage,
  getMessage,
  addMessage,
  updateMessage,
  delMessage,
  readMessage,
  readMessageBatch,
} from "@/api/message/index";
import Editor from "@/components/Editor";
import { listSimpleUsers } from "@/api/system/user";

export default {
  name: "MessageList",
  components: {
    Editor,
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 消息表格数据
      messageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      viewOpen: false,
      // 是否显示添加/编辑对话框
      open: false,
      // 状态选项
      statusOptions: [
        { dictValue: "0", dictLabel: "未读" },
        { dictValue: "1", dictLabel: "已读" },
      ],
      // 类型选项
      typeOptions: [
        { dictValue: "0", dictLabel: "系统通知" },
        { dictValue: "1", dictLabel: "个人消息" },
      ],
      // 用户选项
      userOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        status: undefined,
        type: undefined,
      },
      // 表单参数
      form: {
        messageId: undefined,
        title: undefined,
        content: undefined,
        type: "0",
        receiverId: undefined,
        status: "0",
        createTime: undefined,
        typeLabel: undefined,
      },
      // 表单规则
      rules: {
        title: [
          { required: true, message: "消息标题不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "消息内容不能为空", trigger: "blur" },
        ],
        type: [
          { required: true, message: "消息类型不能为空", trigger: "change" },
        ],
        receiverId: [
          { required: true, message: "接收人不能为空", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    markReadDisabled() {
      return this.ids.length > 0;
    },
    removeDisabled() {
      return this.ids.length > 0;
    },
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询消息列表 */
    getList() {
      this.loading = true;
      listMessage(this.queryParams).then((response) => {
        this.messageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.messageId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 查看按钮操作 */
    handleView(row) {
      getMessage(row.messageId).then((response) => {
        this.form = response.data;
        this.form.typeLabel = this.parseMessageType(this.form);
        this.viewOpen = true;
        // 如果是未读消息，标记为已读
        if (row.status === "0") {
          this.handleRead(row, false);
        }
      });
    },
    /** 添加按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加消息";
      // 获取用户列表用于个人消息
      listSimpleUsers().then((response) => {
        this.userOptions = response.data;
      });
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      this.reset();
      getMessage(row.messageId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改消息";
        // 获取用户列表用于个人消息
        listSimpleUsers().then((response) => {
          this.userOptions = response.data;
        });
      });
    },
    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.messageId) {
            updateMessage(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMessage(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const messageIds = row.messageId || this.ids;
      this.$modal
        .confirm('是否确认删除消息编号为"' + messageIds + '"的数据项?')
        .then(() => {
          return delMessage(messageIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 标记消息为已读 */
    handleRead(row, showMsg = true) {
      readMessage(row.messageId).then(() => {
        if (showMsg) {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        } else {
          // 静默更新列表
          this.messageList.forEach((item) => {
            if (item.messageId === row.messageId) {
              item.status = "1";
            }
          });
        }
      });
    },
    /** 标记多个消息为已读 */
    handleReadBatch() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择需要标记已读的消息");
        return;
      }
      readMessageBatch(this.ids).then(() => {
        this.$modal.msgSuccess("操作成功");
        this.getList();
      });
    },
    /** 重置表单 */
    reset() {
      this.form = {
        messageId: undefined,
        title: undefined,
        content: undefined,
        type: "0",
        receiverId: undefined,
        status: "0",
      };
      this.resetForm("form");
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    // 解析消息类型
    parseMessageType(row) {
      let typeLabel = "";
      this.typeOptions.forEach((item) => {
        if (item.dictValue === row.type) {
          typeLabel = item.dictLabel;
        }
      });
      return typeLabel;
    },
    parseTime,
  },
};
</script>

<style scoped>
.message-detail {
  padding: 0 20px;
}
.message-title {
  text-align: center;
  margin-bottom: 20px;
}
.message-meta {
  display: flex;
  justify-content: space-between;
  color: #666;
  margin-bottom: 20px;
  font-size: 14px;
}
.message-content {
  line-height: 1.6;
  min-height: 200px;
}
</style>
